package com.lc.guessTheWords.rank;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;

import com.lc.guessTheWords.rank.GetRankInRangeAsyncTask.Param;

public class GetRankInRangeAsyncTask extends
		AsyncTask<Param, Integer, List<RankInfo>> {
	@Override
	protected List<RankInfo> doInBackground(Param... params) {
		if (params != null && params.length > 0) {
			Param param = params[0];
			try {
				List<RankInfo> ranks = new ArrayList<RankInfo>();
				String url = String.format("%s%s?type=%d&start=%d&count=%d",
						SAEHelper.SAE_SERVER_URL,
						SAEHelper.GET_RANK_IN_RANGE_URL, param.type,
						param.start, param.count);
				URL feedUrl = new URL(url);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(feedUrl.openConnection()
								.getInputStream()));
				String str = "";
				int i = param.start + 1;
				while ((str = reader.readLine()) != null) {
					String[] cols = str.split(",");
					if (cols != null && cols.length == 3) {
						RankInfo info = new RankInfo();
						try {
							String name = cols[0];
							String id = cols[1];
							int score = Integer.parseInt(cols[2]);
							info.setNo(i);
							info.setName(name);
							info.setScore(score);
							info.setSelf(false);
							ranks.add(info);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					i++;
				}
				return ranks;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	protected void onPostExecute(List<RankInfo> ranks) {
		if (ranks != null) {
			try {
				// 更新本地数据库，刷新排行界面
				// RankHelper.updateNearbyRank(ranks);
				// MenuScene.getInstance().getRankLayer().updateNearbyRank(RankHelper.getNearbyRank());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public class Param {
		public int type;
		public int start;
		public int count;
	}
}
